package com.desire.test;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author desire
 */
public class _27_条形码 {
    public static void main(String[] args) throws IOException, WriterException {
        String name = "C:\\Users\\desire\\Desktop\\javaProject\\01-javaBase\\src\\main\\resources\\bar.png";
        String content = "6923790798701";
        int width = 300;
        int height = 100;
        // 生成条形码  BarcodeFormat.QR_CODE 二维码  BarcodeFormat.EAN_13条形码
        BitMatrix bm = new MultiFormatWriter().encode(content, BarcodeFormat.EAN_13, width, height);
        MatrixToImageWriter.writeToStream(bm, "png", new FileOutputStream(name));

        // 读到刚生成的条形码
        BufferedImage bar2 = ImageIO.read(new File(name));
        BufferedImage bar = new BufferedImage(bar2.getWidth(), bar2.getHeight() + 30, 1);

        // 创建 画笔
        Graphics2D g = bar.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);

        // 画成类似商品的条形码 (有长短,带数字)
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, bar2.getWidth(), bar2.getHeight() + 30);
        g.drawImage(bar2, 0, 15, bar2.getWidth(), bar2.getHeight(), null);
        g.fillRect(62, 100, 85, 15);
        g.fillRect(155, 100, 83, 15);
        g.setColor(Color.BLACK);
        g.setFont(new Font("", Font.PLAIN, 22));

        // 将信息写入到指定的位置
        g.drawString(content.substring(0, 1), 40, 120);
        g.drawString(content.substring(1, 7), 68, 120);
        g.drawString(content.substring(7), 158, 120);
        g.dispose();
        String to = "C:\\Users\\desire\\Desktop\\javaProject\\01-javaBase\\src\\main\\resources\\bar.png";
        ImageIO.write(bar, "png", new File(to));

        //解析条码
        try {
            BufferedImage image = ImageIO.read(new File(to));
            BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Result result = new MultiFormatReader().decode(bitmap);
            System.out.println(result);
        } catch (IOException | NotFoundException e) {
            e.printStackTrace();
        }
    }
}
